<!-- 定位组件 -->
<template>
	<view class="position flex">
		详细位置
		<image src="/static/images/position.png" mode="aspectFill" class="position-icon" 
		@click="getLocation"
		></image>
		<text>{{currentLocation}}</text>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import {getAddress} from '@/utils/apis.js'
	
	const props = defineProps({
		title: String
	})
	
	// 使用 defineModel 实现双向绑定
	const modelValue = defineModel({
		type: String,
		default: ''
	})
	
	const currentLocation = ref(modelValue.value || '当前位置');
	
	// 获得当前位置经纬度
	async function getLocation(){
		try {
			const location = await new Promise((resolve, reject) => {
				uni.getLocation({
					type: 'wgs84',
					success: function (res) {
						const lat = res.latitude;
						const lon = res.longitude;
						resolve(`${lat},${lon}`);
					},
					fail: function(res) {
						reject(new Error('获取位置失败'));
					}
				});
			});
			
			const params = {
				key:'VTRBZ-DKKW7-FGAXW-HYYGP-JD2M6-MIBZ4',
				location
			}
			
			const addressRes = await getAddress(params);
			
			if(addressRes.message === 'Success'){
				currentLocation.value = addressRes.result.address;
				// 更新双向绑定的值
				modelValue.value = currentLocation.value;
			} else {
				uni.showToast({
					title: '获取地址失败',
					icon: 'none'
				})
			}
		} catch(err) {
			console.error('获取位置失败', err);
			uni.showToast({
				title: '获取位置失败',
				icon: 'none'
			})
		}
	}
</script>

<style lang="scss" scoped>
	.position{
		margin-bottom: 30rpx;
		&-icon{
			width: 30rpx;
			height: 30rpx;
			margin: 0 18rpx;
		}
	}
</style>